package com.alog.storage.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.alog.storage.StorageApplication;
import com.alog.storage.ui.dialog.LoadingDialog;
import com.alog.storage.utils.CommonUtil;

/**
 * Fragment基类，所有Fragment继承此类
 */
public abstract class BaseFragment extends Fragment {
    private View mPreserveView;
    protected Activity mContext;
    private Dialog mLoadingDlg;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mPreserveView != null) {
            return mPreserveView;
        } else {
            return onInitView(inflater, container);
        }
    }

    /**
     * 子Fragment必须实现此方法，初始化View
     *
     * @param inflater
     * @param container
     * @return
     */
    public abstract View onInitView(LayoutInflater inflater, ViewGroup container);

    private Dialog getLoadingDialog(boolean cancelable) {
        if (mLoadingDlg == null) {
            mLoadingDlg = LoadingDialog.createDialog(mContext, LoadingDialog.ProgressStyle.LOTTERY_COMMON, cancelable);
        }
        return mLoadingDlg;
    }

    /**
     * 子类调用网络API时，调用此方法显示加载框
     *
     * @param msg 加载框显示文本，可不传
     */
    public void loadDataStarted(String... msg) {
        if (!mContext.isFinishing()) {
            ((LoadingDialog) getLoadingDialog(true)).setLoadInfo(msg != null && msg.length > 0 ? msg[0] : "正在加载...");
            getLoadingDialog(true).show();
        }
    }

    /**
     * 子类调用网络API完成后，调用此方法隐藏加载框
     */
    public void loadDataComplete() {
        if (!mContext.isFinishing() && mLoadingDlg != null && mLoadingDlg.isShowing()) {
            mLoadingDlg.dismiss();
        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        saveBg();
    }

    private void saveBg() {
        StorageApplication application = (StorageApplication) mContext.getApplication();
        application.setBgBitmap(CommonUtil.takeScreenShot(mContext));
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        saveBg();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPreserveView = getView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
